package com.railway.switchs.action.system;


import com.railway.switchs.constant.FileConstant;
import com.railway.switchs.domain.response.FileUploadResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName FileUploadAction
 * @Author 魏梓晟
 * @Version 1.0
 **/
@Slf4j
@Controller
@RequestMapping("/back/upload")
public class FileUploadAction{

    @Value("${file.upload.path}")
    private String path ;

    /**
     * 单个文件上传
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/singleFileUpload")
    public FileUploadResponse singleFileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request)throws Exception{
        FileUploadResponse response = new FileUploadResponse();
        try{
            Map<String,String> fileInfoMap = new HashMap<>();
            file.transferTo(new File(path+file.getOriginalFilename()));
            response.setCode(FileConstant.FILE_UPLOAD_SUCCESS);
            fileInfoMap.put(FileConstant.FILE_UPLOAD_SRC,FileConstant.FILE_PATH_MAPPING+file.getOriginalFilename());
            fileInfoMap.put(FileConstant.FILE_UPLOAD_TITLE,file.getOriginalFilename());
            response.setData(fileInfoMap);
        }catch (Exception e){
            log.info("上传文件{}失败",file.getOriginalFilename());
            log.error("单文件上传失败：",e);
            response.setCode(FileConstant.FILE_UPLOAD_ERROR);
            response.setMsg("文件上传异常");
        }
        return response;
    }
}
